package org.ms.springboot.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Aspect
@Component
public class LogAspect {

    @Pointcut("execution(public * org.ms.springboot.aop.AopDemoController.*(..))")
    public void log() {
    }

    @Before("log()")
    public void before(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.info("url: {}", request.getRequestURL());
        log.info("method: {}", request.getMethod());
        log.info("ip: {}", request.getRemoteAddr());
        log.info("类名: {}", joinPoint.getSignature().getDeclaringTypeName());
        log.info("方法名: {}", joinPoint.getSignature().getName());
        log.info("请求参数: {}", joinPoint.getArgs());
        log.info("请求参数: {}", joinPoint.getArgs());
    }

    @After("log()")
    public void after() {
        log.info("input after");
    }

    /**
     * 拦截返回对象
     *
     * @param object
     */
    @AfterReturning(returning = "object", pointcut = "log()")
    public void returning(Object object) {
        log.info("response：{}", object);
    }

}
